import { ref, nextTick } from "vue";
import { useFormData } from "@/utils/use-form-data";

/**
 * 使用编辑功能的钩子
 * @param {Object} options - 配置选项
 * @param {Object} options.formFields - 表单字段的初始值
 * @param {Object} options.apis - 包含不同操作（如添加、更新）的API函数
 * @param {Function} options.detailApi - 获取详情的API函数
 * @param {String} [options.idField="id"] - 数据项的唯一标识字段
 * @returns {Object} - 返回表单、表单引用、加载状态及相关操作方法
 */
export function useEdit(options) {
  const { formFields, apis, detailApi, idField = "id" } = options;
  const [form, resetFields, assignFields] = useFormData({ ...formFields });
  const formRef = ref(null);
  const loading = ref(false);

  // 通用API调用方法
  const callWithLoading = async (apiFunc, ...args) => {
    loading.value = true;
    try {
      console.log("args", args);
      return await apiFunc(...args);
    } catch (error) {
      console.log(error);
      // EleMessage.error(error?.message || "提交失败");
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const reloadForm = async () => {
    const res = await callWithLoading(detailApi, form[idField]);
    return res;
  };

  // 通用表单数据加载方法
  const loadFormData = async (id) => {
    if (!id) {
      console.log("初始化表单", formFields, form);
      resetFields(formFields);
      return;
    }
    const res = await callWithLoading(detailApi, id);
    console.log(res, "res");
    assignFields(res);
    // Object.assign(form, res);
    console.log("form", form);
  };

  const validateForm = () => formRef.value?.validate();
  const clearValidateForm = () => formRef.value?.clearValidate();
  const getFormData = () => form;

  const resetForm = async () => {
    await loadFormData(form[idField]);
    clearValidateForm();
    await nextTick();
  };

  const open = async (data) => {
    await loadFormData(data?.[idField]);
    await nextTick();
  };

  const handleSubmit = async (action, formData) => {
    await validateForm();
    const apiFunc = apis[action]?.api;
    if (!apiFunc) return;
    return callWithLoading(apiFunc, formData)
      .then((res) => {
        console.log(res, "res");
      })
      .catch((error) => {
        console.log(error, "error");
        throw error;
      });
  };

  return {
    form,
    resetFields,
    assignFields,
    formRef,
    loading,
    open,
    resetForm,
    handleSubmit,
    validateForm,
    getFormData,
    clearValidateForm,
    reloadForm,
  };
}
